package com.luomu.base.biz.cookBook.redisLock.serverImpl;

import com.alibaba.fastjson.JSON;
import com.luomu.base.api.cookBook.redisLock.RedisLockServer;
import com.luomu.base.biz.cookBook.redisLock.constant.RedisLock;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@RestController
@RequestMapping("/redisLockServer")
public class RedisLockServerImpl implements RedisLockServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockServerImpl.class);

    @Autowired
    @Qualifier("asyncTaskExecutor")
    private Executor asyncTaskExecutor;

    @Override
    public void redisLockMethod(String uuid){
        RLock lock = null;
        String lockKey = "lockKey".concat(uuid);
        LOGGER.info("----------lockKey："+uuid);
        try {
            lock = RedisLock.acquire(lockKey);

            LOGGER.info(JSON.toJSONString(lock.isLocked()));
            LOGGER.info(JSON.toJSONString(lock));

            Thread.sleep(15000);

//            if (lock.isLocked()) {
//                throw new ZTBusinessException("系统繁忙，请稍后重试"); // 或返回错误码
//            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(lock != null) {
                    RedisLock.release(lockKey);
                }
            } catch (Exception e) {
                LOGGER.error("释放Redis锁失败");
            }
        }



    }

    @Override
    public void test() {



        //异步运行一个任务使用CompletableFuture.runAsync方法 没有返回值
        CompletableFuture.runAsync(() -> {
            MDC.put("traceId", "11111111111111");
            LOGGER.info("Hello CompletableFuture!");
            this.redisLockMethod("1");
        },asyncTaskExecutor);

        //异步运行一个任务使用CompletableFuture.runAsync方法 没有返回值
        CompletableFuture.runAsync(() -> {
            MDC.put("traceId", "222222222222222");
            LOGGER.info("Hello CompletableFuture!");
            this.redisLockMethod("1");
        },asyncTaskExecutor);

        //异步运行一个任务使用CompletableFuture.runAsync方法 没有返回值
        CompletableFuture.runAsync(() -> {
            MDC.put("traceId", "333333333333333333");
            LOGGER.info("Hello CompletableFuture!");
            this.redisLockMethod("2");
        },asyncTaskExecutor);

    }


}
